package com.ice.work.moment.crawler.processor;

import com.honeybee.cloud.framework.common.enums.DataStatusEnum;
import com.honeybee.cloud.framework.common.idwork.IdWorker;
import com.ice.work.moment.crawler.service.IlPositionTypeService;
import com.ice.work.moment.facade.crawler.analytical.PositionTypeAnalyticalObject;
import com.ice.work.moment.facade.crawler.dto.PositionTypeDTO;
import com.ice.work.moment.facade.crawler.mapper.AnalyticalObjectConvertMapper;
import com.ice.work.moment.facade.crawler.model.PositionType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description 机构持仓类型
 * @Author DELL
 * @Create 2019-04-29
 * @Since 1.0.0
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class PositionTypeProcessor extends BaseProcessor implements PageProcessor {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private IlPositionTypeService typeService;

    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        log.info("机构持仓类型原文:{}", html.get());
        //机构持仓股
        List<Selectable> oneDivSelectableList = html.xpath("//*[@id='A0A1934A1939A5396_sub']").nodes();
        //基金重仓股
        List<Selectable> twoDivSelectableList = html.xpath("//*[@id='A0A1934A1937_sub']").nodes();
        List<Selectable> divSelectableList = Lists.newArrayList();

        if (CollectionUtils.isNotEmpty(oneDivSelectableList)) {
            divSelectableList.addAll(oneDivSelectableList);
        }
        if (CollectionUtils.isNotEmpty(twoDivSelectableList)) {
            divSelectableList.addAll(twoDivSelectableList);
        }

        if (CollectionUtils.isEmpty(divSelectableList)) {
            return;
        }
        int i = 0;
        do {
            try {
                Selectable divSelectable = divSelectableList.get(i);

                List<Selectable> parentSelectableList = null;
                List<Selectable> childrenSelectableList = null;
                if (i < CollectionUtils.size(oneDivSelectableList)) {
                    parentSelectableList = divSelectable.xpath("//div[@class='t3']").nodes();
                    childrenSelectableList = divSelectable.xpath("//div[@class='d3']").nodes();
                } else {
                    //基金重仓股 需要额外处理
                    parentSelectableList = divSelectable.xpath("//div[@class='t2']").nodes();
                    childrenSelectableList = divSelectable.xpath("//div[@class='d2']").nodes();
                    if (CollectionUtils.isNotEmpty(parentSelectableList)) {
                        parentSelectableList = parentSelectableList.subList(0, 1);
                    }
                    if (CollectionUtils.isNotEmpty(childrenSelectableList)) {
                        childrenSelectableList = childrenSelectableList.subList(0, 1);
                    }
                }
                i++;

                if (CollectionUtils.isEmpty(parentSelectableList)) {
                    continue;
                }
                for (int j = 0; j < parentSelectableList.size(); j++) {
                    Selectable parentSelectable = parentSelectableList.get(j);
                    PositionTypeAnalyticalObject parentObj = getValues(parentSelectable);
                    if (StringUtils.isEmpty(parentObj.getValue())) {
                        continue;
                    }
                    PositionType parentType = AnalyticalObjectConvertMapper.INSTANCE.toModel(parentObj);
                    parentType.setId(idWorker.nextId());
                    parentType.setCreateAt(new Date());
                    parentType.setDataStatus(DataStatusEnum.VALID.key);
                    boolean isSuccess = typeService.saveOrUpdate(parentType);
                    if (!isSuccess) {
                        continue;
                    }
                    PositionTypeDTO parentTypeDTO = typeService.findByValue(parentType.getValue());
                    if (Objects.isNull(parentTypeDTO)) {
                        continue;
                    }
                    if (CollectionUtils.isEmpty(parentSelectableList)) {
                        continue;
                    }
                    if (j > childrenSelectableList.size()) {
                        continue;
                    }
                    Selectable childrenSelecttable = childrenSelectableList.get(j);
                    List<Selectable> childrendSelectableList = childrenSelecttable.xpath("//div[@class='b']").nodes();
                    if (CollectionUtils.isEmpty(childrendSelectableList)) {
                        //基金重仓股的处理方式
                        childrendSelectableList = childrenSelecttable.xpath("//div[@class='t3']").nodes();
                    }
                    if (CollectionUtils.isEmpty(childrendSelectableList)) {
                        continue;
                    }
                    for (Selectable childrendSelectable : childrendSelectableList) {
                       PositionTypeAnalyticalObject childrenObj = getValues(childrendSelectable);
                        if (StringUtils.isEmpty(childrenObj.getValue())) {
                            continue;
                        }
                        PositionType childrenType = AnalyticalObjectConvertMapper.INSTANCE.toModel(childrenObj);
                        childrenType.setId(idWorker.nextId());
                        childrenType.setCreateAt(new Date());
                        childrenType.setDataStatus(DataStatusEnum.VALID.key);
                        childrenType.setParentId(parentTypeDTO.getId());
                        typeService.saveOrUpdate(childrenType);
                    }
                }

            } catch (Exception e) {
                log.error("爬取机构持仓类型异常", e);
            }

        } while (i < divSelectableList.size());

    }

    /**
     * 获取列值
     *
     * @param divSelectable
     * @return
     */
    private PositionTypeAnalyticalObject getValues(Selectable divSelectable) {
        PositionTypeAnalyticalObject obj = new PositionTypeAnalyticalObject();

        obj.setValue(divSelectable.xpath("//div/@id").get());
        String name = null;
        List<Selectable> nobrSelectableList = divSelectable.xpath("//nobr").nodes();
        if (CollectionUtils.isEmpty(nobrSelectableList)) {
            return obj;
        }
        Selectable nobrSelectable = nobrSelectableList.get(0);
        List<Selectable> aSelectable = nobrSelectable.xpath("//a").nodes();
        if (CollectionUtils.isNotEmpty(aSelectable)) {
            name = nobrSelectable.xpath("//a/text()").get();
        }
        if (StringUtils.isEmpty(name)) {
            List<Selectable> spanSelectable = nobrSelectable.xpath("//span").nodes();
            if (CollectionUtils.isNotEmpty(spanSelectable)) {
                name = nobrSelectable.xpath("//span/text()").get();
            }
        }
        obj.setName(name);
        return obj;
    }

    private String getTextPath(String path) {
        String textPath = path + "/text()";
        return textPath;
    }


}
